package com.train.mgr.modules.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.train.common.constant.UserConstants;
import com.train.common.exception.BizException;
import com.train.common.exception.BusinessException;
import com.train.common.model.PageResult;
import com.train.common.utils.AuthUtils;
import com.train.common.utils.StringUtils;
import com.train.mgr.modules.system.dto.request.DeptImportDTO;
import com.train.mgr.modules.system.dto.request.DeptPageReqDto;
import com.train.mgr.modules.system.dto.request.DeptReqDTO;
import com.train.mgr.modules.system.dto.response.DeptListRespDTO;
import com.train.mgr.modules.system.dto.response.TreeNode;
import com.train.mgr.modules.system.entity.Dept;
import com.train.mgr.modules.system.entity.Role;
import com.train.mgr.modules.system.entity.User;
import com.train.mgr.modules.system.mapper.DeptMapper;
import com.train.mgr.modules.system.mapper.RoleMapper;
import com.train.mgr.modules.system.mapper.UserMapper;
import com.train.mgr.modules.system.service.DeptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 部门管理 服务实现
 * 类名拼写错误-加错就错吧
 * @author cxg
 */
@Slf4j
@Service("detpService")
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询部门管理数据
     * @return 部门信息集合
     */
    @Override
    public PageResult<DeptListRespDTO> selectDeptList(DeptPageReqDto params) {
        Long customerId = AuthUtils.getCurrentUser().getCustomerId();
        log.info("customerId:{}",customerId);
        if(ObjectUtil.isEmpty(AuthUtils.getCurrentUser().getCustomerId()) || customerId <=0){
            throw new BizException("客户ID为空，数据异常");
        }
        params.setCustomerId(AuthUtils.getCurrentUser().getCustomerId());
        Page<DeptListRespDTO> page = params.buildPage();
        Page<DeptListRespDTO> resultPage = deptMapper.selectList(page,params);
        List<DeptListRespDTO> deptList = resultPage.getRecords();
        for(DeptListRespDTO dept : deptList){
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
            queryWrapper.eq(User::getDeptId,dept.getDeptId());
            Long empCount = userMapper.selectCount(queryWrapper);
            dept.setEmployeeNumber(empCount);
        }
        return PageResult.of(resultPage, DeptListRespDTO.class);
    }

    /**
     * 查询部门树结构信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeNode> selectDeptTreeList() {
        List<TreeNode> deptList = deptMapper.selectTreeList(AuthUtils.getCurrentUser().getCustomerId());
        List<TreeNode> treeNodeList = new ArrayList<TreeNode>();
        for (TreeNode result : deptList) {
            if (result.getParentId() == 0) {
                treeNodeList.add(buildDeptTree(result, deptList));
            }
        }
        return treeNodeList;
    }

    private TreeNode buildDeptTree(TreeNode result, List<TreeNode> list) {
        for (TreeNode node : list) {
            //如果父类主键等于传过来实体类的ID
            if (node.getParentId().equals(result.getDeptId())) {
                if (result.getChildren() == null) {
                    result.setChildren(new ArrayList<>());
                }
                LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
                queryWrapper.eq(User::getDeptId,node.getDeptId());
                Long empCount = userMapper.selectCount(queryWrapper);
                node.setEmployeeCount(empCount);
                // 递归调用
                result.getChildren().add(buildDeptTree(node, list));
            }
        }
        return result;
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId) {
        Role role = roleMapper.selectById(roleId);
       // return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
        return null;
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public Dept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    @Override
    public Dept selectDeptByParentIdCustomId(Long customId) {
        return deptMapper.selectDeptByParentIdCustomId(customId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId)
    {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(DeptReqDTO dept) {
        Long customerId =AuthUtils.getCurrentUser().getCustomerId();
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        Dept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId(),customerId);
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(DeptReqDTO dept) {
        Dept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new BusinessException("部门停用，不允许新增");
        }
        Dept deptBean = new  Dept();
        BeanUtils.copyProperties(dept,deptBean);
        deptBean.setAncestors(info.getAncestors() + "," + dept.getParentId());
        deptBean.setCreateBy(AuthUtils.getUsername());
        deptBean.setCustomerId(AuthUtils.getCurrentUser().getCustomerId());
        return deptMapper.insertDept(deptBean);
    }

    @Override
    public int insertDefaultDept(Long customerId,String companyName){
        Dept dept = new Dept();
        dept.setCustomerId(customerId);
        dept.setDeptName(companyName);
        dept.setParentId(0L);
        dept.setAncestors("0");
        dept.setCreateBy(AuthUtils.getUsername());
        return deptMapper.insertDept(dept);
    }

    @Override
    public int updateCompanyDeptName(Long customerId,String companyName){
       return deptMapper.updateCompanyDeptName(customerId,companyName);
    }

    /**
     * 修改保存部门信息
     *
     * @param dto 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(DeptReqDTO dto) {
        Dept newParentDept = deptMapper.selectDeptById(dto.getParentId());
        Dept oldDept = deptMapper.selectDeptById(dto.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            oldDept.setAncestors(newAncestors);
            updateDeptChildren(dto.getDeptId(), newAncestors, oldAncestors);
        }
        BeanUtils.copyProperties(dto,oldDept);
        oldDept.setUpdateBy(AuthUtils.getUsername());
        int result = deptMapper.updateDept(oldDept);
        if (StringUtils.isNotEmpty(oldDept.getAncestors()) && !StringUtils.equals("0", oldDept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(oldDept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(Dept dept) {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<Dept> children = deptMapper.selectChildrenDeptById(deptId);
        for (Dept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }

    @Override
    public List<Dept> selectAllChildrenDeptById(Long deptId) {
        return deptMapper.selectAllChildrenDeptById(deptId);
    }
    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId){
        return deptMapper.deleteDeptById(deptId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<Dept> list, Dept t) {
        // 得到子节点列表
        List<Dept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Dept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Dept> getChildList(List<Dept> list, Dept t){
        List<Dept> tlist = new ArrayList<Dept>();
        Iterator<Dept> it = list.iterator();
        while (it.hasNext()) {
            Dept n = (Dept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Dept> list, Dept t)
    {
        return getChildList(list, t).size() > 0;
    }

    @Override
    public List<Long> findChildIdList(Long deptId){
        List<Long> allList =new ArrayList<Long>();
        String splitStr = deptMapper.selectChildIdList(deptId);
        if(StringUtils.isNotBlank(splitStr)){
            String[] array = splitStr.split(",");
            for (String str : array) {
                allList.add(Long.parseLong(str));
            }
        }
        allList.add(deptId);//追加自己的ID
        log.info("findChildIdList allList:{}",allList);
        return allList;
    }


    /**
     * 导入下属单位
     * @param importList
     * @return
     */
    public boolean saveExcelData(Long deptId,List<DeptImportDTO> importList){
       this.checkImportData(deptId,importList);
       //根据部门ID获取部门ID
       Dept parentDept = deptMapper.selectDeptById(deptId);
       if(ObjectUtil.isEmpty(parentDept)){
           throw new BusinessException("上级单位ID查询不到～");
       }
       Long customerId =AuthUtils.getCurrentUser().getCustomerId();
       String createUserName = AuthUtils.getUsername();
       String newAncestors = parentDept.getAncestors() + "," + parentDept.getDeptId();
       for(DeptImportDTO importBean : importList){
           Dept newBean = new Dept();
           newBean.setCustomerId(customerId);
           newBean.setAncestors(newAncestors);
           newBean.setParentId(deptId);
           newBean.setDeptName(importBean.getDeptName());
           newBean.setCreateTime(new Date());
           newBean.setCreateBy(createUserName);
           deptMapper.insertDept(newBean);
       }
       return true;
    }

    /**
     * 导入的数据验证
     * @param deptId
     * @param importList
     */
    private void checkImportData(Long deptId,List<DeptImportDTO> importList){
        if(deptId == null || deptId ==0){
            throw new BusinessException("上级单位ID不能为空");
        }
        if(CollectionUtil.isEmpty(importList)){
            throw new BusinessException("没有要导入的单位名称");
        }
        Long customerId =AuthUtils.getCurrentUser().getCustomerId();
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<importList.size();i++){
            DeptImportDTO importBean = importList.get(i);
            String line = "第【"+(i+1)+"】行，";
            if(StringUtils.isEmpty(importBean.getDeptName())){
                sb.append(line + "【单位名称是空值】；");
            }
            Dept deptDb = deptMapper.checkDeptNameUnique(importBean.getDeptName(), 0L,customerId);
            if(StringUtils.isNotNull(deptDb)){
                sb.append(line + "【单位名称["+importBean.getDeptName()+"]重复】；");
            }
            if(StringUtils.isNotBlank(sb)){
                throw new BusinessException(sb.toString());
            }
        }
    }
}
